// 智能童话书增强JS功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎭 智能童话书系统已加载');
    
    // 获取DOM元素
    const storyForm = document.getElementById('storyForm');
    const welcomeMessage = document.getElementById('welcomeMessage');
    const loadingMessage = document.getElementById('loadingMessage');
    const storyContent = document.getElementById('storyContent');
    
    // 统计元素
    const totalStoriesEl = document.getElementById('totalStories');
    const userSessionsEl = document.getElementById('userSessions');
    const averageRatingEl = document.getElementById('averageRating');
    const systemStatusEl = document.getElementById('systemStatus');
    
    // 表单提交处理
    if (storyForm) {
        storyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            generateStory();
        });
    }
    
    // 生成故事函数
    async function generateStory() {
        try {
            console.log('🚀 开始生成故事...');
            
            // 显示加载状态
            showLoading();
            
            // 获取表单数据
            const formData = new FormData(storyForm);
            const characters = formData.get('characters').split(',').map(c => c.trim()).filter(c => c);
            
            const requestData = {
                theme: formData.get('theme'),
                characters: characters,
                age_group: formData.get('ageGroup') || '6-8岁',
                emotional_focus: 'positive'
            };
            
            console.log('📝 请求数据:', requestData);
            
            // 发送API请求
            const response = await fetch('/api/generate_story', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });
            
            const result = await response.json();
            console.log('📖 故事生成结果:', result);
            
            if (result.success) {
                displayStory(result.data);
                updateStats();
            } else {
                throw new Error(result.error || '故事生成失败');
            }
            
        } catch (error) {
            console.error('❌ 故事生成错误:', error);
            showError(error.message);
        }
    }
    
    // 显示加载状态
    function showLoading() {
        if (welcomeMessage) welcomeMessage.style.display = 'none';
        if (storyContent) storyContent.style.display = 'none';
        if (loadingMessage) loadingMessage.style.display = 'block';
    }
    
    // 显示故事内容
    function displayStory(storyData) {
        console.log('🎭 显示故事:', storyData);
        
        if (!storyContent) return;
        
        // 隐藏加载状态
        if (loadingMessage) loadingMessage.style.display = 'none';
        
        // 构建故事HTML
        const storyHTML = buildStoryHTML(storyData);
        
        storyContent.innerHTML = storyHTML;
        storyContent.style.display = 'block';
    }
    
    // 构建故事HTML
    function buildStoryHTML(storyData) {
        return `
            <div class="story-header mb-4">
                <h3 class="text-primary">
                    <i class="bi bi-book-half"></i> ${storyData.title || '精彩童话故事'}
                </h3>
                <div class="story-meta">
                    <span class="badge bg-primary me-2">
                        <i class="bi bi-brain"></i> ERNIE智能引擎
                    </span>
                    <span class="badge bg-success me-2">
                        <i class="bi bi-star-fill"></i> ${Math.round((storyData.quality_score?.overall || 0.9) * 100)}分
                    </span>
                    <span class="badge bg-info">
                        <i class="bi bi-people"></i> ${storyData.characters?.length || 1}个角色
                    </span>
                </div>
            </div>
            
            <div class="story-text mb-4">
                <div class="story-content-box p-4 bg-light rounded">
                    ${formatStoryText(storyData.story || '故事生成中...')}
                </div>
            </div>
            
            ${buildCharactersSection(storyData.characters)}
            ${buildEducationalSection(storyData.educational_insights)}
            ${buildStructureSection(storyData.story_structure)}
            
            <div class="story-actions text-center">
                <button class="btn btn-primary me-2" onclick="generateNewStory()">
                    <i class="bi bi-arrow-clockwise"></i> 生成新故事
                </button>
                <button class="btn btn-outline-secondary me-2" onclick="shareStory()">
                    <i class="bi bi-share"></i> 分享故事
                </button>
                <button class="btn btn-outline-success" onclick="rateStory()">
                    <i class="bi bi-star"></i> 评价故事
                </button>
            </div>
        `;
    }
    
    // 辅助函数
    window.buildCharactersSection = function(characters) {
        if (!characters) return '';
        return `
            <div class="characters-section mb-4">
                <h5><i class="bi bi-people-fill"></i> 故事角色</h5>
                <div class="row">
                    ${characters.map(char => `
                        <div class="col-md-6 mb-2">
                            <div class="character-card p-3 bg-white rounded shadow-sm">
                                <h6 class="mb-1">${char.name}</h6>
                                <small class="text-muted">
                                    ${char.traits ? char.traits.join('、') : '善良勇敢'}
                                </small>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    };
    
    window.buildEducationalSection = function(insights) {
        if (!insights) return '';
        return `
            <div class="educational-section mb-4">
                <h5><i class="bi bi-lightbulb"></i> 教育价值</h5>
                <div class="insights-list">
                    ${insights.map(insight => `
                        <div class="insight-item p-2 mb-2 bg-info bg-opacity-10 rounded">
                            <i class="bi bi-check-circle text-success me-2"></i>
                            ${insight}
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    };
    
    window.buildStructureSection = function(structure) {
        if (!structure) return '';
        return `
            <div class="structure-section mb-4">
                <h5><i class="bi bi-diagram-3"></i> 故事结构</h5>
                <div class="row">
                    <div class="col-md-4">
                        <div class="structure-card p-3 bg-primary bg-opacity-10 rounded text-center">
                            <h6>第一幕</h6>
                            <small>${structure.act1}</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="structure-card p-3 bg-warning bg-opacity-10 rounded text-center">
                            <h6>第二幕</h6>
                            <small>${structure.act2}</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="structure-card p-3 bg-success bg-opacity-10 rounded text-center">
                            <h6>第三幕</h6>
                            <small>${structure.act3}</small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    };
    
});